package com.hecate.common.db.basedao.provider.delete;

import com.hecate.base.enums.StatusEnum;
import com.hecate.base.utils.GsonUtil;
import com.hecate.common.db.basedao.provider.HecateSqlHelper;
import com.hecate.common.db.basedao.provider.IdListProvider;
import org.apache.ibatis.mapping.MappedStatement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;

/**
 * hecate通用基础删除实现类
 *
 * @author 黄星星
 * @date 2020-12-17
 */
public class HecateBaseDeleteProvider extends MapperTemplate {

    private Logger logger = LoggerFactory.getLogger(HecateBaseDeleteProvider.class);


    public HecateBaseDeleteProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    /**
     * 逻辑删除
     * @param ms
     * @return
     */
    public String delete(MappedStatement ms) {
        final Class<?> entityClass = getEntityClass(ms);
        String tableName = tableName(entityClass);
        return HecateSqlHelper.updateTable(entityClass, tableName) +
                "<set> `gmt_update` = now(), `status` = " + StatusEnum.DISABLE .getCode() +
                " </set>" +
                HecateSqlHelper.wherePKColumns(entityClass);
    }

    /**
     * 物理删除
     *
     * @param mappedStatement
     * @return
     */
    public String doRealDelete(MappedStatement mappedStatement) {
        // 获取操作数据对象
        final Class<?> entityClass = getEntityClass(mappedStatement);
        StringBuilder sql = new StringBuilder();
        String tableName = tableName(entityClass);
        sql.append(HecateSqlHelper.deleteFromTable(entityClass, tableName));
        sql.append(HecateSqlHelper.wherePKColumns(entityClass));
        String sqlStr = sql.toString();
        logger.warn("**************  物理删除:{}", GsonUtil.toJson(sqlStr));
        return sqlStr;

    }

    /**
     * 根据主键字符串进行删除，类中只有存在一个带有@Id注解的字段
     *
     * @param ms
     * @return
     */
    public String deleteByBidList(MappedStatement ms) {
        final Class<?> entityClass = getEntityClass(ms);
        StringBuilder sql = new StringBuilder();
        sql.append(HecateSqlHelper.updateTable(entityClass, tableName(entityClass)) +
                "<set> `gmt_update` = now(), `status` = " + StatusEnum.DISABLE .getCode() +
                " </set>" );
        IdListProvider.appendWhereIdList(sql, entityClass, getConfig().isSafeDelete());
        return sql.toString();
    }
}
